package com.wechat.order.util.headCodeUtil;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by zzy on 2017/12/21.
 */
@Slf4j
@Controller
public class ORcode {

    @RequestMapping(value = "phoneversion/getTwoDimension",method={RequestMethod.POST,RequestMethod.GET})
    public void getTwoDimensionForIOSs(HttpServletRequest request, HttpServletResponse response,
                                       @RequestParam(value = "url",required = false,defaultValue = "" ) String url){

        try {
           getTwoDimension(url, response, 200, 200);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     *  生成web版本二维码
     * @param url 要生成二维码的路径
     * @param response response对象
     * @param width 二维码宽度
     * @param height 二维码高度
     * @throws IOException
     */
    public void getTwoDimension(String url, HttpServletResponse response, int width, int height) throws IOException {
        if (url != null && !"".equals(url)) {
            ServletOutputStream stream = null;
            try {
                stream = response.getOutputStream();
                QRCodeWriter writer = new QRCodeWriter();
                BitMatrix m = writer.encode(url, BarcodeFormat.QR_CODE, height, width);
                MatrixToImageWriter.writeToStream(m, "png", stream);
            } catch (WriterException e) {
                e.printStackTrace();
                log.error("生成二维码失败!");
            } finally {
                if (stream != null) {
                    stream.flush();
                    stream.close();
                }
            }
        }
    }
}
